﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using AtlTestLib;

namespace UseATLCOM
{
    class Program
    {

        class UseDemo : AtlTestLib.ICallback {
            void ICallback.Show(int sum)
            {
                Console.WriteLine("show="+sum);
            }
        }

        /// <summary>
        /// 修改STA,MTA, 验证com的调用模式，
        /// </summary>
        /// <param name="args"></param>
        [MTAThread()]
        static void Main(string[] args)
        {
            var v = new AtlTestLib.AtlDemo();//同一个com对象
            var use = new UseDemo();
            v.addCallback(use);//设置回调接口，outcoming interface
            v.ShowNum(6);//调用函数

            Thread t = new Thread(x =>
            {
                Run((AtlTestLib.IAtlDemo)x);
            });
            t.SetApartmentState(ApartmentState.STA);
            t.Start(v);

            Thread.Sleep(3000);

            Thread t2 = new Thread(x =>
            {
                Run((AtlTestLib.IAtlDemo)x);
            });
            t2.SetApartmentState(ApartmentState.STA);//设置STA模型，
            t2.Start(v);

            Console.ReadKey();
        }

        static public void Run(AtlTestLib.IAtlDemo sc)
        {
            try
            {
                //在某线程内连续调用5次hello函数
                for (var i = 0; i < 5; i++)
                {
                    Console.WriteLine(string.Format("-start,tid={0}", Thread.CurrentThread.ManagedThreadId));

                    //如果此时sc正在被另外的线程调用那么当前线程会卡住等待前一个线程结束
                    Console.WriteLine(string.Format("[{0}] {1}",
                        Thread.CurrentThread.ManagedThreadId,
                        sc.Hello()));

                    Console.WriteLine(string.Format("-end,tid={0}", Thread.CurrentThread.ManagedThreadId));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}
